<template>
  <div class="home-bg">
    <div class="home-header">
      工作台
      <van-icon name="scan" class="scan-icon" @click="onScan" />
    </div>
    <van-search v-model="value" placeholder="搜索流程" class="home-search" />
    <div class="home-stats">
      <div class="stat-card orange" @click="goDaiban('todo')">
        <div class="stat-icon"><van-icon name="notes-o" /></div>
        <div class="stat-title">待我处理</div>
        <div class="stat-num">{{ todoCount }}</div>
      </div>
      <div class="stat-card blue" @click="goDaiban('mine')">
        <div class="stat-icon"><van-icon name="user-o" /></div>
        <div class="stat-title">我发起的</div>
        <div class="stat-num">{{ mineCount }}</div>
      </div>
      <div class="stat-card purple" @click="goDaiban('cc')">
        <div class="stat-icon"><van-icon name="friends-o" /></div>
        <div class="stat-title">抄送我的</div>
        <div class="stat-num">{{ ccCount }}</div>
      </div>
    </div>
    <van-collapse v-model="activeGroups" class="home-group-list">
      <van-collapse-item
        v-for="group in groups"
        :key="group.name"
        :title="group.name + '（' + group.items.length + '）'"
        :name="group.name"
        toggle="true"
      >
        <div class="group-items">
          <div
            class="group-item"
            v-for="item in group.items"
            :key="item.title"
            @click="goFlowDetail(item)"
          >
            <div class="item-icon"><van-icon name="cluster-o" /></div>
            <div class="item-title" :title="item.title">{{ item.title }}</div>
          </div>
        </div>
      </van-collapse-item>
    </van-collapse>

    <!-- 支付宝风格扫码弹窗 -->
    <van-popup
      v-model="isScanVisible"
      position="bottom"
      :style="{ height: '100%' }"
      @close="stopScan"
      @opened="initScanElements"
    >
      <div class="scan-container">
        <!-- 顶部导航 -->
        <div class="scan-header">
          <van-icon name="close" @click="stopScan" class="close-btn" />
          <div class="scan-title">扫一扫</div>
          <div class="scan-help" @click="showHelp">
            <van-icon name="question-circle-o" />
          </div>
        </div>
        
        <!-- 相机容器 -->
        <div class="camera-container">
          <video id="scanVideo" autoplay playsinline></video>
          <canvas id="scanCanvas" class="hidden"></canvas>
          <!-- 半透明遮罩 -->
          <div class="scan-mask">
            <div class="scan-viewfinder">
              <!-- 四角标记 -->
              <div class="corner top-left"></div>
              <div class="corner top-right"></div>
              <div class="corner bottom-left"></div>
              <div class="corner bottom-right"></div>
              
              <!-- 扫描线 -->
              <div class="scan-line" :style="{ top: scanLinePosition + 'px' }"></div>
              
              <!-- 扫描提示文字 -->
              <div class="scan-guide">将二维码/条形码放入框内</div>
            </div>
          </div>
          
          <!-- 闪光灯按钮 -->
          <div 
            class="flashlight-btn" 
            @click="toggleFlashlight"
            v-if="hasFlashlight"
          >
            <van-icon :name="flashlightOn ? 'lightbulb' : 'lightbulb-o'" />
          </div>
        </div>
        <!-- 底部操作区 -->
        <div class="scan-actions">
          <div class="action-btn" @click="takePhoto">
            <van-icon name="image" class="action-icon" />
            <span class="action-text">相册</span>
          </div>
          <div class="action-btn" @click="switchCamera">
            <van-icon name="refresh" class="action-icon" />
            <span class="action-text">切换</span>
          </div>
          <div class="action-btn" @click="showHistory">
            <van-icon name="clock-o" class="action-icon" />
            <span class="action-text">历史</span>
          </div>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script>
import { getGroupList, getHomeStaticData } from "@/api/api.js";
import jsQR from "jsqr";

export default {
  name: "home",
  data() {
    return {
      value: "",
      activeGroups: [],
      groups: [],
      todoCount: 0,
      mineCount: 0,
      ccCount: 0,
      
      // 扫码相关变量
      isScanVisible: false,
      stream: null,
      video: null,
      canvas: null,
      canvasContext: null,
      isScanning: false,
      scanTimer: null,
      scanAnimationTimer: null,
      currentCamera: "environment",
      cameras: [],
      scanLinePosition: 0,
      scanLineDirection: 1,
      flashlightOn: false,
      hasFlashlight: false,
      mediaTrack: null
    };
  },
  created() {
    this.fetchGroups();
    this.fetchHomeStaticData();
  },
  beforeDestroy() {
    this.stopScan();
  },
  methods: {
    async fetchGroups() {
      try {
        const res = await getGroupList();
        console.log(res);
        if (res.data && (res.status === 0 || res.success)) {
          const raw = res.data || [];
          this.groups = raw
            .map((item) => ({
              name: item.name,
              items: (item.groups || []).map((flow) => ({
                id: flow.id,
                title: flow.name,
                imgUrl: flow.imgUrl,
              })),
            }))
            .filter((g) => g.items.length > 0);
          
          if (this.groups.length > 0) {
            this.activeGroups = [this.groups[0].name];
          }
        } else {
          this.$toast("获取分组失败");
        }
      } catch (e) {
        console.error("获取分组异常:", e);
        this.$toast("获取分组异常");
      }
    },
    async fetchHomeStaticData() {
      try {
        const res = await getHomeStaticData();
        console.log("统计数据:", res);
        if (res.data && (res.status === 0 || res.success)) {
          this.todoCount = res.data.todoNum || 0;
          this.mineCount = res.data.initiatedNum || 0;
          this.ccCount = res.data.ccNum || 0;
        }
      } catch (e) {
        console.error("获取统计数据异常:", e);
        this.$toast("获取数据异常");
      }
    },
    goFlowDetail(item) {
      this.$router.push({
        path: "/flowCreate",
        query: { id: item.id },
      });
    },
    goDaiban(type) {
      this.$router.push({ path: "/task", query: { type } });
    },
    async onScan() {
      if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
        this.$toast("您的浏览器不支持访问相机");
        return;
      }
      
      try {
        this.cameras = await navigator.mediaDevices.enumerateDevices();
        this.isScanVisible = true;
      } catch (error) {
        console.error("扫码初始化失败:", error);
        this.$toast("无法初始化扫码功能: " + error.message);
      }
    },
    initScanElements() {
      this.video = document.getElementById("scanVideo");
      this.canvas = document.getElementById("scanCanvas");
      
      if (this.canvas) {
        try {
          this.canvasContext = this.canvas.getContext("2d");
          this.startScan();
        } catch (error) {
          console.error("获取canvas上下文失败:", error);
          this.$toast("扫码组件初始化失败");
        }
      } else {
        console.error("未找到scanCanvas元素");
        this.$toast("扫码组件初始化失败");
      }
    },
    async startScan() {
      if (!this.video || !this.canvas || !this.canvasContext) {
        this.$toast("扫码组件未准备好");
        return;
      }
      
      try {
        if (this.stream) {
          this.stream.getTracks().forEach(track => track.stop());
        }
        // 请求相机权限
        this.stream = await navigator.mediaDevices.getUserMedia({
          video: { 
            facingMode: this.currentCamera,
            width: { ideal: 1280 },
            height: { ideal: 720 },
            torch: false
          }
        });
        
        // 检测闪光灯
        this.mediaTrack = this.stream.getVideoTracks()[0];
        this.hasFlashlight = this.mediaTrack && this.mediaTrack.getCapabilities().torch;
        
        this.video.srcObject = this.stream;
        
        // 初始化扫描动画
        this.isScanning = true;
        this.scanLinePosition = 50;
        this.startScanAnimation();
        this.startDecode();
        
      } catch (error) {
        console.error("启动相机失败:", error);
        this.$toast("无法访问相机: " + error.message);
        this.isScanVisible = false;
      }
    },
    // 扫描线动画
    startScanAnimation() {
      if (this.scanAnimationTimer) {
        clearInterval(this.scanAnimationTimer);
      }
      const viewfinderHeight = 240;
      const animationSpeed = 2;
      this.scanAnimationTimer = setInterval(() => {
        this.scanLinePosition += this.scanLineDirection * animationSpeed;
        if (this.scanLinePosition >= viewfinderHeight - 10) {
          this.scanLineDirection = -1;
        } else if (this.scanLinePosition <= 10) {
          this.scanLineDirection = 1;
        }
      }, 20);
    },
    startDecode() {
      if (this.scanTimer) {
        clearInterval(this.scanTimer);
      }
      
      this.scanTimer = setInterval(() => {
        if (this.video && this.video.readyState === this.video.HAVE_ENOUGH_DATA) {
          this.canvas.width = this.video.videoWidth;
          this.canvas.height = this.video.videoHeight;
          this.canvasContext.drawImage(this.video, 0, 0, this.canvas.width, this.canvas.height);
          
          const imageData = this.canvasContext.getImageData(0, 0, this.canvas.width, this.canvas.height);
          const code = jsQR(imageData.data, imageData.width, imageData.height, {
            inversionAttempts: "dontInvert",
          });
          
          if (code) {
            this.handleScanResult(code.data);
          }
        }
      }, 300);
    },
    // 闪光灯控制
    async toggleFlashlight() {
      if (!this.mediaTrack || !this.hasFlashlight) return;
      
      try {
        this.flashlightOn = !this.flashlightOn;
        await this.mediaTrack.applyConstraints({
          advanced: [{ torch: this.flashlightOn }]
        });
      } catch (error) {
        console.error("控制闪光灯失败:", error);
        this.$toast("无法控制闪光灯");
      }
    },
    handleScanResult(result) {
      // 扫描成功动画
      this.scanSuccessAnimation();
      
      setTimeout(() => {
        this.stopScan();
        console.log("扫码结果:", result);
        // this.$toast(`扫码成功: ${result}`);
        window.location.href = result;
        // 例如: 根据扫码结果跳转页面
        // this.$router.push({ path: '/flowDetail', query: { processInstanceId: result,taskId:result } });
      }, 800);
    },
    // 扫描成功动画
    scanSuccessAnimation() {
      this.isScanning = false;
      const viewfinder = document.querySelector('.scan-viewfinder');
      if (viewfinder) {
        viewfinder.classList.add('success');
        setTimeout(() => {
          viewfinder.classList.remove('success');
        }, 800);
      }
    },
    stopScan() {
      this.isScanning = false;
      
      // 清除定时器
      if (this.scanTimer) clearInterval(this.scanTimer);
      if (this.scanAnimationTimer) clearInterval(this.scanAnimationTimer);
      
      // 关闭闪光灯
      if (this.mediaTrack && this.flashlightOn) {
        this.mediaTrack.applyConstraints({ advanced: [{ torch: false }] })
          .catch(err => console.error("关闭闪光灯失败:", err));
        this.flashlightOn = false;
      }
      
      // 停止视频流
      if (this.stream) {
        this.stream.getTracks().forEach(track => track.stop());
        this.stream = null;
        this.mediaTrack = null;
      }
      
      if (this.video) this.video.srcObject = null;
      this.isScanVisible = false;
    },
    restartScan() {
      this.startScan();
    },
    switchCamera() {
      this.currentCamera = this.currentCamera === "environment" ? "user" : "environment";
      this.flashlightOn = false;
      this.startScan();
    },
    takePhoto() {
      this.stopScan();
      
      const fileInput = document.createElement('input');
      fileInput.type = 'file';
      fileInput.accept = 'image/*';
      
      fileInput.onchange = (e) => {
        const file = e.target.files[0];
        if (file) {
          this.decodeImageFile(file);
        }
        fileInput.remove();
      };
      
      fileInput.click();
    },
    decodeImageFile(file) {
      const reader = new FileReader();
      
      reader.onload = (event) => {
        const img = new Image();
        
        img.onload = () => {
          if (!this.canvas || !this.canvasContext) {
            this.initScanElements();
          }
          
          this.canvas.width = img.width;
          this.canvas.height = img.height;
          this.canvasContext.drawImage(img, 0, 0, img.width, img.height);
          
          const imageData = this.canvasContext.getImageData(0, 0, img.width, img.height);
          const code = jsQR(imageData.data, imageData.width, imageData.height, {
            inversionAttempts: "dontInvert",
          });
          
          if (code) {
            this.handleScanResult(code.data);
          } else {
            this.$toast("未识别到二维码");
            setTimeout(() => {
              this.onScan();
            }, 500);
          }
        };
        
        img.src = event.target.result;
      };
      
      reader.readAsDataURL(file);
    },
    showHelp() {
      this.$toast("将二维码/条形码对准扫描框即可自动识别");
    },
    showHistory() {
      this.$toast("暂无扫描历史");
    }
  },
};
</script>
<style scoped>
.home-bg {
  background: #f6f8fa;
  min-height: 100vh;
  padding-bottom: 0;
}
.home-header {
  background: #1677ff;
  color: #fff;
  font-size: 22px;
  font-weight: bold;
  text-align: center;
  padding: 18px 0 12px 0;
  letter-spacing: 2px;
  position: relative;
}
.scan-icon {
  position: absolute;
  right: 16px;
  top: 50%;
  transform: translateY(-50%);
  font-size: 24px;
  color: #fff;
  cursor: pointer;
}
.home-search {
  margin: 16px 12px 12px 12px;
  border-radius: 24px;
  background: #fff;
}
.home-stats {
  display: flex;
  justify-content: space-between;
  margin: 0 12px 18px 12px;
  gap: 10px;
}
.stat-card {
  flex: 1;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 8px #1677ff11;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 10px 0 8px 0;
  cursor: pointer;
  transition: transform 0.2s;
}
.stat-card:active {
  transform: scale(0.98);
}
.stat-card .stat-icon {
  font-size: 28px;
  margin-bottom: 4px;
}
.stat-card.orange .stat-icon {
  color: #ff9800;
}
.stat-card.blue .stat-icon {
  color: #1677ff;
}
.stat-card.purple .stat-icon {
  color: #8e24aa;
}
.stat-title {
  font-size: 13px;
  color: #666;
}
.stat-num {
  font-size: 18px;
  font-weight: bold;
  color: #222;
  margin-top: 4px;
}
.home-group-list {
  margin: 0 0 20px 0;
  background: #fff;
}
.group-items {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  margin: 8px 12px;
  padding-bottom: 8px;
}
.group-item {
  width: 70px;
  display: flex;
  flex-direction: column;
  align-items: center;
  cursor: pointer;
  padding: 8px 0;
}
.group-item:active {
  background-color: #f5f5f5;
  border-radius: 8px;
}
.item-icon {
  background: #e3f2fd;
  border-radius: 12px;
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 22px;
  margin-bottom: 4px;
  color: #1677ff;
}
.item-title {
  font-size: 13px;
  color: #333;
  text-align: center;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  width: 100%;
}

/* 支付宝风格扫码样式 */
.scan-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: #000;
}

/* 顶部导航 */
.scan-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  background-color: rgba(0, 0, 0, 0.5);
  color: #fff;
}

.close-btn {
  font-size: 24px;
  color: #fff;
}

.scan-title {
  font-size: 18px;
  font-weight: 500;
  color: #fff;
}

.scan-help {
  font-size: 20px;
  color: #fff;
}

/* 相机容器 */
.camera-container {
  flex: 1;
  position: relative;
  overflow: hidden;
}

#scanVideo {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

/* 半透明遮罩 */
.scan-mask {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: 
    linear-gradient(to top, rgba(0, 0, 0, 0.6), rgba(0, 0, 0, 0.6)),
    linear-gradient(to bottom, rgba(0, 0, 0, 0.6), rgba(0, 0, 0, 0.6)),
    linear-gradient(to left, rgba(0, 0, 0, 0.6), rgba(0, 0, 0, 0.6)),
    linear-gradient(to right, rgba(0, 0, 0, 0.6), rgba(0, 0, 0, 0.6));
  background-position: 
    0 0, 0 0, 0 0, 0 0;
  background-size: 
    100% calc(50% - 120px), 
    100% calc(50% - 120px), 
    calc(50% - 120px) 240px, 
    calc(50% - 120px) 240px;
  background-repeat: no-repeat;
  background-origin: content-box;
  padding: calc(50% - 120px) calc(50% - 120px);
}

/* 扫描框 */
.scan-viewfinder {
  width: 240px;
  height: 240px;
  position: relative;
}

/* 四角标记 */
.corner {
  width: 24px;
  height: 24px;
  position: absolute;
  border: 3px solid #00C853; /* 支付宝绿色 */
  z-index: 2;
}

.top-left {
  top: 0;
  left: 0;
  border-right: none;
  border-bottom: none;
  border-radius: 4px 0 0 0;
}

.top-right {
  top: 0;
  right: 0;
  border-left: none;
  border-bottom: none;
  border-radius: 0 4px 0 0;
}

.bottom-left {
  bottom: 0;
  left: 0;
  border-right: none;
  border-top: none;
  border-radius: 0 0 0 4px;
}

.bottom-right {
  bottom: 0;
  right: 0;
  border-left: none;
  border-top: none;
  border-radius: 0 0 4px 0;
}

/* 扫描线 */
.scan-line {
  position: absolute;
  left: 0;
  width: 100%;
  height: 3px;
  background: linear-gradient(90deg, transparent, #00C853, transparent);
  box-shadow: 0 0 10px 1px #00C853;
  z-index: 1;
  transition: top 0.02s linear;
}

/* 扫描提示文字 */
.scan-guide {
  position: absolute;
  bottom: -40px;
  left: 0;
  width: 100%;
  text-align: center;
  color: #fff;
  font-size: 14px;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.5);
}

/* 闪光灯按钮 */
.flashlight-btn {
  position: absolute;
  top: 20px;
  right: 20px;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: rgba(0, 0, 0, 0.3);
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  font-size: 20px;
  backdrop-filter: blur(5px);
  z-index: 3;
}

/* 底部操作区 */
.scan-actions {
  display: flex;
  justify-content: space-around;
  padding: 15px 0 25px;
  background-color: rgba(0, 0, 0, 0.8);
  backdrop-filter: blur(10px);
}

.action-btn {
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #fff;
  width: 60px;
}

.action-icon {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: rgba(255, 255, 255, 0.15);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  margin-bottom: 5px;
}

.action-text {
  font-size: 12px;
  color: #eee;
}

/* 扫描成功动画 */
.scan-viewfinder.success {
  animation: scanSuccess 0.8s ease;
}

@keyframes scanSuccess {
  0% {
    box-shadow: 0 0 0 0 rgba(0, 200, 83, 0.5);
  }
  70% {
    box-shadow: 0 0 0 20px rgba(0, 200, 83, 0);
  }
  100% {
    box-shadow: 0 0 0 0 rgba(0, 200, 83, 0);
  }
}

.hidden {
  display: none;
}
</style>
